package com.example.cloud.service.business.medical.impl;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.medical.ExecuteRecordRepository;
import com.example.cloud.dao.business.medical.TreatPlanCourseProductRepository;
import com.example.cloud.dao.finance.ChargeDetailsRepository;
import com.example.cloud.model.basic.Product;
import com.example.cloud.model.business.medical.ExecuteRecord;
import com.example.cloud.model.business.medical.TreatPlanCourseProduct;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.finance.ChargeDetails;
import com.example.cloud.model.member.Member;
import com.example.cloud.service.basic.info.MemberService;
import com.example.cloud.service.business.medical.ExecuteService;
import com.example.cloud.service.business.medical.TreatPlanCourseProductService;
import com.example.cloud.utils.BusinessUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class TreatPlanCourseProductServiceImpl implements TreatPlanCourseProductService {

    private static final Logger logger = Logger.getLogger(TreatPlanCourseProductServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private ExecuteService executeService;

    @Autowired
    private ExecuteRecordRepository executeRecordRepository;

    @Autowired
    private TreatPlanCourseProductRepository treatPlanCourseProductRepository;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ChargeDetailsRepository chargeDetailsRepository;

    @Override
    public TreatPlanCourseProduct findOne(Long id) {
        return treatPlanCourseProductRepository.findOne(id);
    }

    @Override
    public TreatPlanCourseProduct doSave(TreatPlanCourseProduct record) {
        record.setCreationTime(null);
        BusinessUtil.appendRecord(record);
        return treatPlanCourseProductRepository.save(record);
    }

    @Override
    @Transactional
    public void batchInsert(List<TreatPlanCourseProduct> records, Long patientId) {
        for (TreatPlanCourseProduct record : records) {
            record.setId(null);
            record.setPatientId(patientId);
            // 设置会员信息
            ChargeDetails details = new ChargeDetails();
            Member member = memberService.findByPatientId(patientId);
            if(member != null){
                record.setMemberId(member.getId());
                details.setMemberId(member.getId());
            }
            record.setTotalPrice(record.getPrice().multiply(new BigDecimal(record.getQuantity())));
            record.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            record.setCreationTime(null);
            BusinessUtil.appendRecord(record);
            treatPlanCourseProductRepository.save(record);

            // 创建收费
            generateChargeDetails(record, patientId, details);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void generateChargeDetails(TreatPlanCourseProduct record, Long patientId, ChargeDetails details){
        details.setPatientId(patientId);
        details.setBusinessId(record.getId());
        details.setBusinessType(StateConstants.CHARGE_BUSINESS_TYPE_COURSE);
        details.setChargeType(StateConstants.CHARGE_CHARGE_TYPE_COURSE_PRODUCT);
        details.setItemId(record.getProductId());
        details.setItemName(record.getProductName());
        details.setQuantity(record.getQuantity());
        details.setPrice(record.getPrice());
        details.setTotalPrice(record.getTotalPrice());
        details.setCreationTime(null);
        BusinessUtil.appendRecord(details);
        chargeDetailsRepository.save(details);
    }

    @Override
    @Transactional
    public Result doDeleteById(Long id) {
        Result result = new Result();
        result.setCode(CommonConstants.SUCCESS);
        result.setMsg("删除成功");
        // 校验删除条件
        boolean check = checkDelete(id);
        if(!check){
            result.setCode(CommonConstants.FAILURE);
            result.setMsg("购买成功后不能删除");
            return result;
        }
        // 逻辑删除
        treatPlanCourseProductRepository.delete(id);
        // 删除待收费
        chargeDetailsRepository.deleteByBusinessIdAndChargeType(id, StateConstants.CHARGE_CHARGE_TYPE_COURSE_PRODUCT);
        return result;
    }

    public boolean checkDelete(Long id){
        boolean check = true;
        TreatPlanCourseProduct record = treatPlanCourseProductRepository.findOne(id);
        // 已付款不能删除
        if(record.getChargeStatus() == StateConstants.CHARGE_STATUS_YES){
            check = false;
        }
        return check;
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 逻辑删除
        StringBuilder sql = new StringBuilder("update treat_plan_course_product set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
    }

    @Override
    @Transactional
    public void doExecute(TreatPlanCourseProduct record, int status, String content) {
        ExecuteRecord executeRecord = new ExecuteRecord();
        executeRecord.setPatientId(record.getPatientId());
        executeRecord.setComplaintId(record.getComplaintId());
        executeRecord.setOrderId(record.getId());
        executeRecord.setStatus(status);
        executeRecord.setTreatType(StateConstants.EXECUTE_TREAT_TYPE_COURSE);
        executeRecord.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PRODUCT);
        executeRecord.setItemId(record.getProductId());
        executeRecord.setItemName(record.getProductName());
        executeRecord.setDoctorName(record.getCreatedBy());
        executeRecord.setDoctorRemark(record.getMedicalAdvice());
        executeRecord.setSource(record.getProductName());
        executeRecord.setTotalCount(record.getQuantity());
        executeRecord.setLaveCount(record.getQuantity() - record.getExecute());
        executeRecord.setMedicalTime(record.getCreationTime());
        executeRecord.setExecuteContent(content);
        executeRecord.setCreationTime(null);
        BusinessUtil.appendRecord(executeRecord);
        executeService.doSave(executeRecord);
        // 更新已执行次数
        if(status == StateConstants.EXECUTE_STATUS_YES){
            record.setExecuteStatus(StateConstants.EXECUTE_STATUS_YES);
            BusinessUtil.appendRecord(record);
            treatPlanCourseProductRepository.save(record);
        }
    }

    @Override
    @Transactional
    public void doStop(Long id) {
        TreatPlanCourseProduct product = treatPlanCourseProductRepository.findOne(id);
        product.setStatus(StateConstants.HOME_DETAILS_STATUS_STOP);
        product.setStopTime(new Date());
        BusinessUtil.appendRecord(product);
        treatPlanCourseProductRepository.save(product);
    }

    @Override
    public void doReplace(Long id, List<Product> list) {
        TreatPlanCourseProduct details = treatPlanCourseProductRepository.findOne(id);
        details.setStatus(StateConstants.HOME_DETAILS_STATUS_REPLACE);
        BusinessUtil.appendRecord(details);
        treatPlanCourseProductRepository.save(details);
        for (Product product : list) {
            TreatPlanCourseProduct cd = new TreatPlanCourseProduct();
            cd.setPatientId(details.getPatientId());
            cd.setMemberId(details.getMemberId());
            cd.setComplaintId(details.getComplaintId());
            cd.setProductId(product.getId());
            cd.setProductName(product.getName());
            cd.setQuantity(product.getQuantity());
            cd.setPrice(product.getPrice());
            cd.setTotalPrice(product.getPrice().multiply(new BigDecimal(product.getQuantity())));
            cd.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            BusinessUtil.appendRecord(cd);
            treatPlanCourseProductRepository.save(cd);
        }
    }
}
